package com.atguigu.gmall.util;

import com.atguigu.gmall.common.Constant;
import net.minidev.json.JSONObject;
import org.apache.commons.beanutils.BeanUtils;

import java.lang.reflect.InvocationTargetException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/7/30 15:10
 */
public class JdbcUtil {
    public static void main(String[] args) throws SQLException, ClassNotFoundException, IllegalAccessException, InvocationTargetException, InstantiationException {
        List<JSONObject> list = JdbcUtil
            .queryList(getMysqlConnection(), "select * from spu_info where id = ?", new Object[]{1}, JSONObject.class);
    
        for (JSONObject obj : list) {
    
            System.out.println(obj);
        }
    }
    public static Connection getMysqlConnection() throws ClassNotFoundException, SQLException {
        Class.forName(Constant.MYSQL_DRIVER);
        return DriverManager.getConnection(Constant.MYSQL_URL);
    }
    
    public static Connection getPhoenixConnection() throws ClassNotFoundException, SQLException {
        Class.forName(Constant.PHOENIX_DRIVER);
        return DriverManager.getConnection(Constant.PHOENIX_URL);
    }
    
    public static <T> List<T> queryList(Connection conn, String sql, Object[] args, Class<T> tClass) throws SQLException, IllegalAccessException, InstantiationException, InvocationTargetException {
        List<T> result = new ArrayList<>();
        // 通过一个sql查询数据, 应该得到多行, 每行封装到一个T类型的对象中
        PreparedStatement ps = conn.prepareStatement(sql);
        
        // 1. 给ps的占位符进行赋值
        for (int i = 0; args != null && i < args.length; i++) {
            ps.setObject(i + 1, args[i]);
        }
        
        // 2. 执行sql, 得到结果集      id  name  age
        ResultSet resultSet = ps.executeQuery();
        ResultSetMetaData metaData = resultSet.getMetaData();
        while (resultSet.next()) {
            T t = tClass.newInstance(); // 使用无参构造函数进行创建对象   new User()
    
            for (int i = 1; i <= metaData.getColumnCount(); i++) { // 列的索引从1开始
                String columnName = metaData.getColumnLabel(i);  // 获取列名的别名(如果有)
                Object value = resultSet.getObject(columnName);
                BeanUtils.setProperty(t, columnName, value);
            }
            result.add(t);
        }
        
        return result;
    }
}
